import React, { useState, useEffect } from "react";
import ReactEcharts from "echarts-for-react";
import ChartsWrap from "components/charts/chartsWrap";
import { formatUnits, numberToFixed } from "../../../utils/billUtils";

var colorList = [
  "#afa3f5",
  "#00d488",
  "#3feed4",
  "#3bafff",
  "#f1bb4c",
  "#f06292",
  "#ff80ab",
  "#f44336",
  "#00bcd4",
  "#009688",
  "#40c4ff",
  "#18ffff",
  "#18ffff",
  "#69f0ae",
  "#b2ff59",
  "#eeff41",
  "#00e676",
  "#76ff03",
  "#c6ff00"
];

const PieChart = ({
  title = "数据展示",
  name = "",
  data = []
}) => {
  const [currentColorList, setColorList] = useState([...colorList]);
  const [chartOptions, setChartOptions] = useState({});

  useEffect(() => {
    // 计算填充色
    // 当颜色数据不够时，从中取随机索引的进行填补
    let tempColorList = [...colorList];
    if (data.length > colorList.length) {
      let temp = data.length - colorList.length;
      for (let i = 0; i < temp; i++) {
        tempColorList.push(
          colorList[Math.floor(Math.random() * colorList.length)]
        );
      }
    }
    setColorList(tempColorList);
    setChartOptions(getOption(data));
  }, [data]);

  const getOption = data => {
    let totalPrice = 0; //总价
    const billData = []; // 账单数据数组
    const billDataObj = new Map(); // 根据账单类型，通过对象唯一类型
    const otherData = { value: 0, name: "其他", rate: 0 }; // 小于1%的放入其他

    // 计算总价
    // 将数据根据classid分类
    data.forEach(item => {
      totalPrice += item.price;
      if (billDataObj.hasOwnProperty(item.classid)) {
        billDataObj[item.classid] += item.price;
      } else {
        billDataObj[item.classid] = item.price;
      }
    });

    // 从分类中取出每种类型的花费
    for (let key in billDataObj) {
      let price = billDataObj[key];
      let rate = Math.round((price / totalPrice) * 100);
      if (rate > 1) {
        billData.push({ value: price, name: key });
      } else {
        otherData.value += price;
      }
    }

    if (otherData.value) {
      billData.push(otherData);
    }

    const priceRes = formatUnits(totalPrice);

    return {
      title: {
        text: numberToFixed(priceRes.money) + priceRes.unit,
        subtext: name,
        x: "center",
        y: "center",
        textStyle: {
          fontSize: 30,
          fontWeight: "normal",
          color: ["#333"]
        },
        subtextStyle: {
          color: "#666",
          fontSize: 16
        }
      },
      grid: {
        bottom: 150,
        left: 0,
        right: "10%"
      },
      toolbox: {
        feature: {
          saveAsImage: {
            show: true,
            name: title,
            pixelRatio: 2
          },
          dataView: {}
        }
      },
      legend: {
        show: false,
        orient: "vertical",
        top: "middle",
        right: "5%",
        textStyle: {
          color: "#f2f2f2",
          fontSize: 25
        },
        icon: "roundRect"
      },
      series: [
        // 主要展示层的
        {
          radius: ["35%", "65%"],
          center: ["50%", "50%"],
          type: "pie",
          itemStyle: {
            normal: {
              color: function(params) {
                return currentColorList[params.dataIndex];
              }
            }
          },
          labelLine: {
            normal: {
              show: true,
              length: 15,
              length2: 120,
              lineStyle: {
                color: "#d3d3d3"
              },
              align: "right"
            },
            color: "#000",
            emphasis: {
              show: true
            }
          },
          label: {
            normal: {
              formatter: function(params) {
                var str = "";
                str =
                  "{a|}\n{nameStyle|" +
                  params.name +
                  "}" +
                  "{rate| " +
                  params.percent +
                  "%}";
                return str;
              },
              padding: [0, -130],
              height: 155,
              rich: {
                a: {
                  width: 38,
                  height: 38,
                  lineHeight: 50,
                  align: "left"
                },
                nameStyle: {
                  fontSize: 16,
                  color: "#555",
                  align: "left"
                },
                rate: {
                  fontSize: 20,
                  color: "#1ab4b8",
                  align: "left"
                }
              }
            }
          },
          data: billData
        },
        // 边框的设置
        {
          radius: ["59%", "65%"],
          center: ["50%", "50%"],
          type: "pie",
          label: {
            normal: {
              show: false
            },
            emphasis: {
              show: false
            }
          },
          labelLine: {
            normal: {
              show: false
            },
            emphasis: {
              show: false
            }
          },
          animation: false,
          tooltip: {
            show: false
          },
          itemStyle: {
            normal: {
              color: "rgba(250,250,250,0.5)"
            }
          },
          data: [
            {
              value: 1
            }
          ]
        }
      ]
    };
  };

  return (
    <ChartsWrap
      title={title}
      data={data}
    >
      <ReactEcharts option={chartOptions} />
    </ChartsWrap>
  );
};

export default PieChart;
